package cn.huihuo.weibo.service;

import cn.huihuo.weibo.bean.*;
import cn.huihuo.weibo.bean.productpric.ProductOutSitePrice;
import cn.huihuo.weibo.module.Product;
import cn.huihuo.weibo.module.ProductPic;
import cn.huihuo.weibo.utils.URLParam;
import cn.huihuo.weibo.utils.URLToParamUtil;
import com.google.gson.Gson;
import com.jfinal.kit.PropKit;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Dan
 *
 * Created by zhengjunbo on 2015/9/17.
 */
public class FetchProductProcess implements Runnable{





    private final String url;

    private  final ProductResult productResult;

    public FetchProductProcess(String url,ProductResult productResult) {
        this.productResult = productResult;
        productResult.setData(new Data());

        productResult.setStatus("0");
        productResult.getData().setPercent("");
        this.url = url;
    }

    @Override
    public void run() {
        String percent = "";
        String  status = "0";
        try {
        productResult.getData().setPercent(percent);
        productResult.setStatus(status);
        productResult.getData().setPercent("10%");
            String skuId ;
            try {
                skuId = getSkuId(url);

            } catch (Exception e) {
                productResult.setStatus("2");
                productResult.setDescription("这个网址不是来自：www.amazon.com （美国亚马逊）" +
                        "本网站的抓取程序暂时无 法实现人工智能不限网站地抓取，请谅解");
                return;
            }
            productResult.getData().setPercent("20%");
        Product bySkuId = Product.product.findBySkuId(skuId);
        productResult.getData().setPercent("30%");
        System.out.println("bySkuId:"+bySkuId);



        if(bySkuId!=null){//如果已经爬过
            productResult.getData().setProductName(bySkuId.get("prod_title"));
            productResult.getData().setProductId(String.valueOf(bySkuId.getInt("id")));
            List<ProductPic> pics = ProductPic.productPic.findByProductId(bySkuId.getInt("id"));
            if(pics!=null){
                for(ProductPic productPic:pics){
                    Pic pic = new Pic();
                    pic.setUrl(productPic.get("out_pic_path"));
                    pic.setId(String.valueOf(productPic.getInt("id")));
                    productResult.getData().setPics(pic);//这里添加线程获取图片，并且更新到数据库中
                    break;
                }
            }
            productResult.getData().setPercent("90%");
            productResult.setStatus("1");
            productResult.getData().setPercent("100%");

            System.out.println("run productResult:"+productResult);
            return;
        }


        productResult.getData().setPercent("40%");

            String productJson ;
            try {
                productJson = getProductJson(url);
            } catch (Exception e) {

                productResult.setStatus("2");
                productResult.setDescription("服务器开小差了,请稍后再试！");
                e.printStackTrace();
                return;
            }
            productResult.getData().setPercent("60%");
            Gson gson = new Gson();
            ResultExProduct resultExProduct = gson.fromJson(productJson, ResultExProduct.class);

            System.out.println(productJson);
            ExProduct exProduct = resultExProduct.getExProduct();

            if(resultExProduct.getResultStatus()!=ResultStatus.SUCCESS.getCode()){
                String message="";
                Integer resultStatus = resultExProduct.getResultStatus();
                if(resultStatus==1001){
                    message="这个网址不是来自： Www.amazon.com （美国亚马逊）\n" +
                            "本网站的抓取程序暂时无 法实现人工智能不限网站 地抓取，请谅解";
                }

                if(resultStatus==1002){
                    message = "亚马逊反击了！ 信不信多点一次 抓取 按钮我就能抓到？";
                }
                if(resultStatus==1003){
                    message = "服务器开小差了，请检查商品是否正常！";
                }
                if(resultStatus==1004){
                    message = "该链接不是正确的商品！";
                }
                if(resultStatus == 1099){
                    message = "服务器开小差了！";
                }
                productResult.setStatus("2");
                productResult.setDescription(message);
                return;
            }
            //要把该商品保存进数据库中


            Product product = new Product();
            productResult.getData().setPercent("70%");
            if(exProduct.getImageUrl()==null||exProduct.getImageUrl().size()==0){
                throw new RuntimeException("图片属性为空！");
            }
            product.set("prod_url", url)
                    .set("product_out_id", exProduct.getProductId() == null ? skuId : exProduct.getProductId())
                    .set("prod_title", exProduct.getTitle())
                    .set("price", exProduct.getPrice())
                    .set("sku_id", skuId)
                    .set("price_current", "USD").save();

            String productId = String.valueOf(product.getInt("id"));
            productResult.getData().setProductId(productId);
            productResult.getData().setProductName(exProduct.getTitle());


            productResult.getData().setPercent("80%");

            for(int i=0;i<exProduct.getImageUrl().size();i++){

                ProductPic productPic = new ProductPic();
                productPic.set("prod_id", productId)
                        .set("out_pic_path", exProduct.getImageUrl().get(i)).save();
                Integer picId = productPic.getInt("id");

                DownLoadProductPic.service.addPic(productPic);

                if(i==0){//默认第一张图片
                    Pic pic = new Pic();
                    pic.setUrl(exProduct.getImageUrl().get(i));
                    pic.setId(String.valueOf(picId));
                    productResult.getData().setPics(pic);

                    product.set("defult_pic_id",picId).update();
                }

            }
            ProductOutSitePrice outSitePrice = new ProductOutSitePrice();
            outSitePrice.setUrl(url);
            outSitePrice.setProdId(productId);
            outSitePrice.setSite("bingfan");
            DownProductPrice.service.add(outSitePrice);

            ProductOutSitePrice outSitePrice1 = new ProductOutSitePrice();
            outSitePrice1.setUrl(url);
            outSitePrice1.setProdId(productId);
            outSitePrice1.setSite("hai360");
            DownProductPrice.service.add(outSitePrice1);

            productResult.getData().setPercent("100%");
            productResult.setStatus("1");
        }catch (Throwable e){
            e.printStackTrace();
            productResult.setStatus("2");
            productResult.setDescription("服务器开小差了，请检查商品是否正常！");
        }

    }



    private String getSkuId(String url){
        String skuId = null;
        Pattern filter1 = Pattern.compile("[\\s\\S]*/dp/[\\s\\S]*");
        Pattern filter2 = Pattern.compile("[\\s\\S]*/gp/product/[\\s\\S]*");

        Matcher matcher1 = filter1.matcher(url);
        Matcher matcher2 = filter2.matcher(url);
        boolean match1 = matcher1.find();
        boolean match2 = matcher2.find();
        if(!(match1 || match2)){
            throw new RuntimeException("url error!");
        }
        URL urlObj ;
        try {
            urlObj = new URL(url);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        URLParam urlParam = URLToParamUtil.toParam(urlObj);
        List<String> pathParam = urlParam.getPathParam();
        if(match1){
            int dp = pathParam.indexOf("dp");
            skuId = pathParam.get(dp+1);

        }
        if(match2){
            int gp = pathParam.indexOf("gp");
            skuId = pathParam.get(gp+2);

        }
        return  skuId;
    }


    public String getProductJson(String url)  {

        String str ;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000);
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 120000);
            HttpGet get  = new HttpGet(PropKit.use("config.properties").get("productRequest")+"?url="+url);

            HttpResponse execute = httpClient.execute(get);



            str = EntityUtils.toString(execute.getEntity(), "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return str;
    }

    public ProductResult getProductResult() throws CloneNotSupportedException {
        return (ProductResult) productResult.clone();
    }


}
